package lwk.thread;

import lwk.thread.demo.WebDownloader;

import java.util.concurrent.*;

/**
 * @author:lwk
 * @create: 2022-07-27 21:33
 * @Description: 实现Callable创建线程
 *
 * *****！！好处：可以定义返回值
 *
 * 线程创建方式三：
 * 1、实现Callable接口
 * 2、重写Call()方法
 * 3、创建执行服务
 * 4、提交执行
 * 5、获取结果
 * 6、关闭服务
 */
public class TestThread3 implements Callable<Boolean> {
    private String url; // 网络图片地址
    private String name;// 保存的文件名

    public TestThread3(String url,String name) {
        this.url = url;
        this.name = name;
    }

    // 下载图片线程的执行体
    @Override
    public Boolean call() throws Exception {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url,name);
        System.out.println("下载了文件名为："+name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        TestThread3 t1 = new TestThread3("https://vkceyugu.cdn.bspapp.com/VKCEYUGU-866e71ae-1b42-4371-a1ec-45aca1f0aae6/59c04783-d885-4e57-b351-a962569ffb3a.webp", "1.webp");
        TestThread3 t2 = new TestThread3("https://vkceyugu.cdn.bspapp.com/VKCEYUGU-866e71ae-1b42-4371-a1ec-45aca1f0aae6/59c04783-d885-4e57-b351-a962569ffb3a.webp", "2.webp");
        TestThread3 t3 = new TestThread3("https://vkceyugu.cdn.bspapp.com/VKCEYUGU-866e71ae-1b42-4371-a1ec-45aca1f0aae6/59c04783-d885-4e57-b351-a962569ffb3a.webp", "3.webp");

        // 创建执行服务
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        // 提交执行
        Future<Boolean> r1 = executorService.submit(t1);
        Future<Boolean> r2 = executorService.submit(t2);
        Future<Boolean> r3 = executorService.submit(t3);
        // 获取结果
        Boolean rs1 = r1.get();
        Boolean rs2 = r2.get();
        Boolean rs3 = r3.get();
        // 关闭服务
        executorService.shutdownNow();


    }
}
